import Taro from "@tarojs/taro";
import { wxlogin } from "@/request";
import { View, Text, Button } from "@tarojs/components";
import { useState, useEffect } from "react";
import "./login.less";

const Login = () => {
  const [error, setError] = useState("");
  const [isLoading, setIsLoading] = useState(true);

  const handleLogin = async () => {
    const token = Taro.getStorageSync("token");
    if (token) {
      Taro.switchTab({ url: "/pages/record/record" });
      return;
    }
    const { code } = await Taro.login();
    const res = await wxlogin({ code });
    if (res?.token) {
      Taro.setStorageSync("token", res.token);
      Taro.switchTab({ url: "/pages/record/record" });
    } else {
      setError(res?.error || "登录失败，请重试");
    }
    setIsLoading(false);
  };

  useEffect(() => {
    handleLogin();
  });

  return (
    <View className="login-container">
      {isLoading ? (
        <Text className="loading-text">登录中...</Text>
      ) : error ? (
        <View className="error-container">
          <Text className="error-text">{error}</Text>
          <Button
            className="retry-btn"
            onClick={handleLogin}
            disabled={isLoading}
          >
            重新登录
          </Button>
        </View>
      ) : null}
    </View>
  );
};

export default Login;
